﻿namespace KinonekoSoftware.Platform.Core
{

    public class MultiLineViewModel : ObjectDialog<string>
    {
        private string _text;
        
        protected override bool OnReceive(DialogContext parameter)
        {
            var r    = false;
            
            if (parameter.Has(ContextBase.Key_Value))
            {
                r    = true;
                Text = parameter.GetString(ContextBase.Key_Value);
            }

            if (parameter.Has(DialogContext.Key_Limit))
            {
                Limit = Math.Clamp(parameter.GetInteger(DialogContext.Key_Limit), 0, 512);
                Limit = Limit == 0 ? 200 : Limit;
            }
            else
            {
                Limit = 200;
            }

            
            return r;
        }
        
        protected override void CreateValidationRules(ICollection<DialogRule> rules)
        {
            rules.Add(
                DialogRule.Create<MultiLineViewModel>(
                    TextSR.Dialog_TextNotEmpty, 
                    x => !string.IsNullOrEmpty(x.Text)));
            
            
            rules.Add(
                DialogRule.Create<MultiLineViewModel>(
                    TextSR.Dialog_Text_SoLarge,
                    x =>
                    {
                        var len = x.Text?.Length ?? 0;
                        return len > -1 && len <= Limit;
                    }));
        }
        protected override string OnFinish(bool editing)
        {
            if (editing)
            {
                return _text;
            }

            return _text;
        }
        
        public int Limit { get; set; }

        /// <summary>
        /// 获取或设置 <see cref="Text"/> 属性。
        /// </summary>
        public string Text
        {
            get => _text;
            set => TryFinishAndSetValue(ref _text, value);
        }
    }
}